import os
import json
import redis
from loguru import logger
import allure
import re
from utils.handle_path import CONFIG_DIR
from utils.base_api import BaseApi


class HandleRedis:
    @allure.step('step:连接Redis')
    def __init__(self, **kwargs):

        # 连接到Redis
        try:
            # pool = redis.ConnectionPool()
            self.rediscon = redis.Redis(**kwargs)
        except Exception as e:
            logger.error(f'Redis连接失败，连接参数：{kwargs}')
            raise e



    def get(self, key):
        '''
        获取redis的key值
        :param key:
        :return:
        '''
        return str(self.rediscon.get(key),encoding="utf-8")

    def ttl(self, key):
        '''
        获取redis的key值的过期时间
        :param key:
        :return:t
        '''
        return self.rediscon.ttl(key)

    def keys(self, key):
        '''
        获取redis的key列表
        :param key:
        :return:t
        '''
        return self.rediscon.keys(key)

    def set(self,key,value,ex=None,px=None,nx=None,xx=None):
        '''
        设置redis的key值,可设置过期时间
        :param key:
        :param value:
        :param ex:
        :param px:
        :param nx:
        :param xx:
        :return:
        '''
        self.rediscon.set(key,value,ex,px,nx,xx)


if __name__ == '__main__':
    p = os.path.join(CONFIG_DIR, 'config.yaml')
    a = BaseApi()
    conf = a.get_yaml(p)
    redisconf = conf['redis']
    print(redisconf)
    db = HandleRedis(**redisconf)

    print(db.keys('*-*-*-*-*')[0])
    print(db.ttl(db.keys('*-*-*-*-*')[0]))
    t_keys = db.keys('*-*-*-*-*')
    print('符合图形验证码条件的key总个数：', len(t_keys))

    a = 0
    b = 0
    # 循环遍历符合图形验证码的keys
    for i in range(len(t_keys)):
        key = t_keys[i]
        value = db.get(key)
        ttl = db.ttl(key)
        print(key)
        print(value)
        print(ttl)
        if a < ttl:
            a = ttl
            b = key
    print(a)
    print(db.get(b))

    #db.get(db.keys('*-*-*-*-*'))
    # HandleRedis.set("name", "baba")